package com.yaglyf.mvc.controller.user;

import com.yaglyf.mvc.aop.annotation.Auth;
import com.yaglyf.mvc.controller.vo.Result.Result;
import com.yaglyf.mvc.controller.vo.User;
import com.yaglyf.mvc.controller.vo.UserRegister;
import com.yaglyf.mvc.dao.entity.UserInfo;
import com.yaglyf.mvc.emun.Constant;
import com.yaglyf.mvc.emun.ResultEmun;
import com.yaglyf.mvc.emun.UserEnum;
import com.yaglyf.mvc.service.dto.UserDto;
import com.yaglyf.mvc.service.itf.ILoginService;
import com.yaglyf.mvc.service.itf.IRegisterService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * Title: Class CommentsShow
 * Description:
 * 注释展示类，说明各种方法注释怎么写
 *
 * @author qiang.yang
 * @version 1.0.0
 * @email qiang.yang@chinaredstar.com
 * @date: 2016/10/10 14:46
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private ILoginService loginService;
    @Autowired
    private IRegisterService registerService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "register",method = RequestMethod.POST)
    public ModelAndView register(UserRegister userRegister,ModelAndView mv){

        UserEnum userEnum = registerService.registerUser(userRegister);

        if (userEnum == UserEnum.REG_SUC ){
            mv.setViewName("user/register");
            return mv;
        }
        mv.setViewName("login");
        mv.addObject("err",userEnum);
        return mv;
    }
    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user")
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @Auth
    public ModelAndView login(User user,ModelAndView mv,HttpSession session){
        UserEnum login;
        try {
            UserDto userDto = loginService.login(user);
            login = userDto.getUserEnum();
            if (userDto.getUserInfo() != null){
                session.setAttribute(Constant.J_SESSION.name(),userDto.getUserInfo());
            }
        } catch (Exception e) {
            login= UserEnum.LOGIN_ERR;
        }
        if (login == UserEnum.LOGIN_SUC){
            mv.setViewName("user/index");
            return mv;
        }
        mv.setViewName("login");
        mv.addObject("err",login);
        return mv;
    }

    @RequestMapping(value = "getUserInfo",method = RequestMethod.POST)
    public Result getUserInfo(HttpSession session){
        UserInfo userInfo = (UserInfo)session.getAttribute(Constant.J_SESSION.name());
       return new Result(ResultEmun.SUC,userInfo);
    }
}
